package tornadoj.web;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tornadoj.util.Utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * Created by tinyms on 13-12-18.
 */
public class HttpContext {
    private final static Logger Log = LoggerFactory.getLogger(HttpContext.class);
    //const key
    public final static String SESSION_CURRENT_USER = "__TORNADOJ_CURRENT_USER__";
    //
    private static Configuration freemarkerConfiguration = new Configuration();
    public HttpServletRequest request;
    public HttpServletResponse response;
    public List<String> plainParams = new ArrayList<String>();
    private Map<String, Object> tplData = new HashMap<String, Object>();

    public HttpContext() {
    }

    public HttpContext(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    //freemaker
    public void render(String tplPath) {
        try {
            String cacheTpl = Layout.compile(tplPath);
            Template tpl = freemarkerConfiguration.getTemplate(cacheTpl, "utf-8");
            tpl.process(this.tplData, response.getWriter());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    public void putData(String name, Object data) {
        this.tplData.put(name, data);
    }

    public static Configuration getFreemarkerConfiguration() {
        return freemarkerConfiguration;
    }

    /**
     * 当前登录用户
     *
     * @return 唯一性标识值
     */
    public Object user() {
        return request.getSession().getAttribute(SESSION_CURRENT_USER);
    }

    //Params Get
    public String param(String name, String defaultValue) {
        String val = request.getParameter(name);
        if (StringUtils.isBlank(val)) {
            return defaultValue;
        }
        return val;
    }

    public String param(int index) {
        return this.plainParams.get(index);
    }

    public int paramInt(String name, int defaultValue) {
        return Utils.parseInt(request.getParameter(name), defaultValue);
    }

    public int paramInt(int index) {
        return NumberUtils.toInt(this.plainParams.get(index));
    }

    public float paramFloat(String name, float defaultValue) {
        return Utils.parseFloat(request.getParameter(name), defaultValue);
    }

    public float paramFloat(int index) {
        return NumberUtils.toFloat(this.plainParams.get(index));
    }

    public double paramDouble(String name, double defaultValue) {
        return Utils.parseDouble(request.getParameter(name), defaultValue);
    }

    public double paramDouble(int index) {
        return NumberUtils.toDouble(this.plainParams.get(index));
    }

    public Date paramDate(String name, Date defaultValue) {
        return Utils.parseDate(name, defaultValue);
    }

    public Date paramDate(int index, String formatter) {
        try {
            return DateUtils.parseDate(this.plainParams.get(index), formatter);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Date paramDate(String name, String formatter, Date defaultValue) {
        return Utils.parseDate(name, formatter, defaultValue);
    }

    public Date paramDateTime(String name, Date defaultValue) {
        return Utils.parseDateTime(name, defaultValue);
    }

    /**
     * 转换JSON成Javabean
     * @param json
     * @param c
     * @param <T>
     * @return
     */
    public <T> T paramJson(String json, Class<T> c) {
        return Utils.decode(json, c);
    }

    /**
     * 页面重定向
     * @param targetUrl
     */
    public void redirect(String targetUrl){
        try {
            request.getRequestDispatcher(targetUrl).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册系统异常
     * @param e
     * @param request
     * @param response
     */
    public static void exception(Exception e, HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("javax.servlet.error.exception", e.getCause());
        e.printStackTrace();
    }
}
